let express=require('express')
let fs=require('fs')
let path=require('path')

let postRouter=express.Router()

// 分页
postRouter.get('/list', (req, res) => {
    let { page, count } = req.query

    let filepath = path.join(__dirname, '../json/posts.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let newarr = arr.slice((page - 1) * count, page * count)
    // 总页数
    let total = arr.length
    res.send({ code: 200, msg: '渲染完成', list: newarr, total: total })
})

// 搜索
postRouter.get('/search', (req, res) => {
    let { searchkey} = req.query

    let filepath = path.join(__dirname, '../json/posts.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let newarr = arr.filter((item) => {
        return item.name.includes(searchkey)
    })
    // 查询到的信息的总页数
    let total = newarr.length
    res.send({ code: 200, msg: '查询完毕', list: searcharr, total: total })
})
// 删除
postRouter.post('/delete', (req, res) => {
    let { id } = req.body
    let filepath = path.join(__dirname, '../json/posts.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let i = arr.findIndex((item) => {
        return item.id == id
    })
    arr.splice(i, 1)
    fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8')
    res.send({ code: 200, msg: '删除成功' })
})
module.exports=postRouter